﻿<%@ WebHandler Language="C#" Class="PageUploadPageHandler" %>

using System;
using System.Web;
using System.IO;
using System.Data.SqlClient;
using System.Web.Security;
using System.Runtime.Remoting.Contexts;
using System.Data;
using Newtonsoft.Json;

public class PageUploadPageHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        string ActionSwitch = context.Request.Form["ActionSwitch"];//判斷要求執行的動作
        string strConn = global::LinkToDatabase.strConn;//宣告連線字串
        switch(ActionSwitch)
        {
            case "EditLoad":
                int u_id = Convert.ToInt32(context.Request.Form["u_id"]);
                int page = Convert.ToInt32(context.Request.Form["page"]);
                int article_id = Convert.ToInt32(context.Request.Form["article_id"]);
                //string article_title = "";
                //string article_content = "";
                DataSet ds = new DataSet();
                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    string strCmd = "select unboxing_article_title,unboxing_article_content,product_id from unboxing_article where unboxing_article_id=@article_id and user_id=@u_id";
                    using (SqlDataAdapter da = new SqlDataAdapter(strCmd, conn))
                    {
                        da.SelectCommand.Parameters.AddWithValue("@article_id", article_id);
                        da.SelectCommand.Parameters.AddWithValue("@u_id", u_id);
                        //conn.Open();
                        //SqlDataReader dr = cmd.ExecuteReader();
                        //while (dr.Read())
                        //{
                        //    article_title = dr["unboxing_article_title"].ToString();
                        //    article_content = dr["unboxing_article_content"].ToString();
                        //}
                        da.Fill(ds, "article");
                        //conn.Close();
                    }
                    strCmd = "select [image] from unboxing_image where unboxing_article_id=@article_id";
                    using (SqlDataAdapter da = new SqlDataAdapter(strCmd, conn))
                    {
                        da.SelectCommand.Parameters.AddWithValue("@article_id", article_id);
                        da.Fill(ds, "picture");
                    }
                    
                    //string strCmd2 = "select category_id,category_name from category where unboxing_article_id=@article_id and user_id=@u_id";
                }
                //context.Response.ContentType = "text/html";
                //context.Response.ContentType = "text/javascript";
                //context.Response.Write("$('#TitleTxt').val(" + article_title + ");var Txt = decodeURI(" + article_content + ");setTimeout(function () { CKEDITOR.instances.TextBox1.setData(Txt); }, 1);");
                context.Response.ContentType = "application/json";
                context.Response.Write(JsonConvert.SerializeObject(ds));
                return;
            case "EditPost":
                string EditedTitleTxt = context.Request.Form["TitleTxt"];
                string EditedTxt = context.Request.Form["Txt"];
                string EditedPage = context.Request.Form["Page"];
                int EditedPid = 2, EditedUid = 2, EditedAid = 0;
                EditedUid = Convert.ToInt32(context.Request.Form["Uid"]);
                EditedAid = Convert.ToInt32(context.Request.Form["Aid"]);
                EditedPid = Convert.ToInt32(context.Request.Form["ProductSelect"]);

                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    string strCmd = "update unboxing_article set unboxing_article_title=@TitleTxt,unboxing_article_content=@Txt,product_id=@EditedPid where unboxing_article_id=@EditedAid and user_id=@EditedUid";// unboxing_article(unboxing_article_title,unboxing_article_content,unboxing_article_publish_date,product_id,user_id,view_count) values(@TitleTxt,@Txt, @Date,@Pid,@Uid,0)";
                    using (SqlCommand cmd = new SqlCommand(strCmd, conn))
                    {
                        //System.Text.RegularExpressions.Regex.Replace("/Uploads/","./Uploads/",-1,0);
                        //System.Text.RegularExpressions.Regex rgx =new System.Text.RegularExpressions.Regex()
                        EditedTxt = EditedTxt.Replace("src=%22/Uploads/", "src=%22./Uploads/");
                        cmd.Parameters.AddWithValue("@TitleTxt", EditedTitleTxt);
                        cmd.Parameters.AddWithValue("@Txt", EditedTxt);
                        //cmd.Parameters.AddWithValue("@Date", Date);
                        cmd.Parameters.AddWithValue("@EditedAid", EditedAid);
                        cmd.Parameters.AddWithValue("@EditedUid", EditedUid);
                        cmd.Parameters.AddWithValue("@EditedPid", EditedPid);
                        //cmd.Parameters.AddWithValue("@ImageDataFile", ImageDataFile);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
                context.Response.ContentType = "text/html";
                context.Response.Write("<script>sessionStorage.Title = '';sessionStorage.Txt = '';alert('修改成功！');location.href = '../UserPublishedRecord.aspx?page=" + EditedPage.ToString() + "';</script>");
                return;
            case "EditPostWithImage":
                string EditedTitleTxt2 = context.Request.Form["TitleTxt"];
                string EditedTxt2 = context.Request.Form["Txt"];
                string EditedPage2 = context.Request.Form["Page"];
                int EditedPid2 = 2, EditedUid2 = 2, EditedAid2 = 0;
                EditedUid2 = Convert.ToInt32(context.Request.Form["Uid"]);
                EditedAid2 = Convert.ToInt32(context.Request.Form["Aid"]);
                EditedPid2 = Convert.ToInt32(context.Request.Form["ProductSelect"]);
                HttpPostedFile TitleImg2 = context.Request.Files["TitleImg"];
                string SavePath2 = AppDomain.CurrentDomain.BaseDirectory + "Uploads\\Temp\\Temp" + EditedUid2 + EditedPid2 + TitleImg2.FileName.Substring(0);
                TitleImg2.SaveAs(SavePath2);
                FileStream fs2 = new FileStream(SavePath2, FileMode.Open, FileAccess.Read);
                byte[] buf2 = new byte[fs2.Length];
                fs2.Read(buf2, 0, (int)fs2.Length);
                fs2.Close();
                fs2.Dispose();
                System.IO.File.Delete(SavePath2);
                DataSet dsimg = new DataSet();
                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    string strCmd = "select count(*) as pictureTF from unboxing_image where unboxing_article_id = @article_id";
                    int countimg = 10;
                    using (SqlCommand cmd = new SqlCommand(strCmd, conn))
                    {
                        cmd.Parameters.AddWithValue("@article_id", EditedAid2);
                        conn.Open();
                        SqlDataReader dr = cmd.ExecuteReader();
                        while (dr.Read())
                        {
                            countimg = Convert.ToInt16(dr["pictureTF"].ToString());
                        }
                        conn.Close();
                    }
                    
                    strCmd = "update unboxing_article set unboxing_article_title=@TitleTxt,unboxing_article_content=@Txt,product_id=@EditedPid where unboxing_article_id=@EditedAid and user_id=@EditedUid";
                    using (SqlCommand cmd = new SqlCommand(strCmd, conn))
                    {
                        EditedTxt2 = EditedTxt2.Replace("src=%22/Uploads/", "src=%22./Uploads/");
                        cmd.Parameters.AddWithValue("@TitleTxt", EditedTitleTxt2);
                        cmd.Parameters.AddWithValue("@Txt", EditedTxt2);
                        cmd.Parameters.AddWithValue("@EditedAid", EditedAid2);
                        cmd.Parameters.AddWithValue("@EditedUid", EditedUid2);
                        cmd.Parameters.AddWithValue("@EditedPid", EditedPid2);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                    if (countimg==1)
                    {
                        strCmd = "update unboxing_image set [image]=@buf where [unboxing_article_id]=@Txtid";
                        using (SqlCommand cmd = new SqlCommand(strCmd, conn))
                        {
                            cmd.Parameters.AddWithValue("@Txtid", EditedAid2);
                            cmd.Parameters.AddWithValue("@buf", buf2);
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            conn.Close();
                        }
                    }
                    else if(countimg ==0)
                    {
                        strCmd = "insert into unboxing_image(unboxing_article_id,image) values(@Txtid,@buf)";
                        using (SqlCommand cmd = new SqlCommand(strCmd, conn))
                        {
                            cmd.Parameters.AddWithValue("@Txtid", EditedAid2);
                            cmd.Parameters.AddWithValue("@buf", buf2);
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            conn.Close();
                        }
                    }
                }
                context.Response.ContentType = "text/html";
                context.Response.Write("<script>sessionStorage.Title = '';sessionStorage.Txt = '';alert('修改成功！');location.href = '../UserPublishedRecord.aspx?page=" + EditedPage2.ToString() + "';</script>");
                return;
            case "NewPost":
                string TitleTxt = context.Request.Form["TitleTxt"];
                HttpPostedFile TitleImg = context.Request.Files["TitleImg"];
                string Txt = context.Request.Form["Txt"];
                DateTime Date = DateTime.Now;
                //string Date = DateNow.ToString("yyyy-MM-dd");
                int Pid = 2, Uid = 2;
                Uid = Convert.ToInt32(context.Request.Form["Uid"]);
                Pid = Convert.ToInt32(context.Request.Form["ProductSelect"]);
                if (TitleImg.FileName == "" || TitleImg == null)
                {
                    context.Response.ContentType = "text/html";
                    context.Response.Write("<script>alert('請選擇封面圖。');location.href = '../UploadPage.aspx';</script>");
                    return;
                }
                else
                {
                    string SubName = TitleImg.FileName.Substring(TitleImg.FileName.Length - 3);
                    if (SubName.ToLower() != "jpg" && SubName.ToLower() != "png")
                    {
                        context.Response.ContentType = "text/html";
                        context.Response.Write("<script>alert('上傳檔案格式不符。');location.href = '../UploadPage.aspx';</script>");
                        return;
                    }
                    if (TitleImg.ContentLength > 204800)
                    {
                        context.Response.ContentType = "text/html";
                        context.Response.Write("<script>alert('檔案太大。');location.href = '../UploadPage.aspx';</script>");
                        return;
                    }
                }
                string SavePath = AppDomain.CurrentDomain.BaseDirectory + "Uploads\\Temp\\Temp" + Uid + Pid + TitleImg.FileName.Substring(0);
                TitleImg.SaveAs(SavePath);
                //====================
                //File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + "images\\" + context.Request["TitleImageTest"] + ".jpg", StreamToBytes(context.Request.InputStream));
                //====================
                //if (TitleImg != null)
                //{
                    //檔案轉二進位vvvvv
                    FileStream fs = new FileStream(SavePath, FileMode.Open, FileAccess.Read);
                    byte[] buf = new byte[fs.Length];
                    fs.Read(buf, 0, (int)fs.Length);
                    fs.Close();
                    fs.Dispose();
                    //檔案轉二進位^^^^^（轉好的檔案是buf）
                //}
                    System.IO.File.Delete(SavePath);
        
                //string ImageDataFile = FormsAuthentication.HashPasswordForStoringInConfigFile(Uid.ToString(), "sha1");
                //unboxing_article
                //TitleTxt=標題=unboxing_article_title
                //Txt=已編碼內文=unboxing_article_content
                //Date=上傳日期=unboxing_article_publish_date
        
                //unboxing_image
                //自己抓文章ID=unboxing_article_id
                //buf=圖檔的二進位碼=image
                //
                //==========================================
                //上傳（要改）
                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    int Txtid;
                    string strCmd = "insert into unboxing_article(unboxing_article_title,unboxing_article_content,unboxing_article_publish_date,product_id,user_id,view_count) values(@TitleTxt,@Txt, @Date,@Pid,@Uid,0)";
                    using (SqlCommand cmd = new SqlCommand(strCmd, conn))
                    {
                        //System.Text.RegularExpressions.Regex.Replace("/Uploads/","./Uploads/",-1,0);
                        //System.Text.RegularExpressions.Regex rgx =new System.Text.RegularExpressions.Regex()
                        Txt = Txt.Replace("src=%22/Uploads/", "src=%22./Uploads/");
                        cmd.Parameters.AddWithValue("@TitleTxt", TitleTxt);
                        cmd.Parameters.AddWithValue("@Txt", Txt);
                        cmd.Parameters.AddWithValue("@Date", Date);
                        cmd.Parameters.AddWithValue("@Pid", Pid);
                        cmd.Parameters.AddWithValue("@Uid", Uid);
                        //cmd.Parameters.AddWithValue("@ImageDataFile", ImageDataFile);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                    string strCmd2 = "select unboxing_article_id from unboxing_article where unboxing_article_publish_date=@Date and unboxing_article_title=@TitleTxt and user_id=@Uid";
                    using (SqlCommand cmd = new SqlCommand(strCmd2, conn))
                    {
                        cmd.Parameters.AddWithValue("@TitleTxt", TitleTxt);
                        cmd.Parameters.AddWithValue("@Date", Date);
                        cmd.Parameters.AddWithValue("@Uid", Uid);
                        conn.Open();
                        object tempTxtid = cmd.ExecuteScalar();
                        Txtid = int.Parse(tempTxtid.ToString());
                        conn.Close();
                    }
                    string strCmd3 = "insert into unboxing_image(unboxing_article_id,image) values(@Txtid,@buf)";
                    using (SqlCommand cmd = new SqlCommand(strCmd3, conn))
                    {
                        cmd.Parameters.AddWithValue("@Txtid", Txtid);
                        cmd.Parameters.AddWithValue("@buf", buf);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
                //==========================================
                //System.IO.File.WriteAllText(@"D:\OOO\Title.txt", Title);
                //System.IO.File.WriteAllText(@"D:\OOO\TitleImagePath.txt", TitleImagePath);
                //System.IO.File.WriteAllText(@"D:\OOO\Text.txt", Text);
                //System.IO.File.WriteAllBytes(@"D:\OOO\Textxx.jpg", buf);
        
                //System.IO.File.WriteAllText(@"D:\OOO\TextDecode.txt", HttpUtility.HtmlDecode(Text));
                context.Response.ContentType = "text/html";
                context.Response.Write("<script>sessionStorage.Title = '';sessionStorage.Txt = '';alert('上傳成功！');location.href = '../index.aspx';</script>");
                return;
        }
        
    }
    ////=======================
    //private byte[] StreamToBytes(Stream stream)
    //{
    //    stream.Position = 0;
    //    var buffer = new byte[stream.Length];
    //    for (int totalBytesCopied = 0; totalBytesCopied < stream.Length; )
    //        totalBytesCopied += stream.Read(buffer, totalBytesCopied, Convert.ToInt32(stream.Length) - totalBytesCopied);
    //    return buffer;
    //}
    ////=======================
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}